package io.alexkozlov.jpointfedagent.operator;

import com.fasterxml.jackson.core.JsonProcessingException;
import io.alexkozlov.jpointfedagent.DiscoveryController;
import io.alexkozlov.jpointfedagent.model.crd.ServiceImport;
import io.fabric8.kubernetes.client.KubernetesClient;
import io.fabric8.kubernetes.client.Watcher;
import io.fabric8.kubernetes.client.WatcherException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class ServiceImportWatcher implements Watcher<ServiceImport> {
    private static final Logger LOGGER = LoggerFactory.getLogger(ServiceImportWatcher.class);

    private final DiscoveryController discoveryController;
    private final KubernetesClient client;

    public ServiceImportWatcher(KubernetesClient client, DiscoveryController discoveryController) {
        this.discoveryController = discoveryController;
        this.client = client;
    }

    @Override
    public void eventReceived(Action action, ServiceImport serviceImport) {
        switch (action) {
            case ADDED:
                LOGGER.info("ServiceImport {}.{} added", serviceImport.getMetadata().getName(), serviceImport.getMetadata().getNamespace());
                discoveryController.addServiceImport(serviceImport);
                break;
            case DELETED:
                LOGGER.info("ServiceImport {}.{} deleted", serviceImport.getMetadata().getName(), serviceImport.getMetadata().getNamespace());
                try {
                    discoveryController.removeServiceImport(serviceImport);
                } catch (JsonProcessingException e) {
                    throw new RuntimeException(e);
                }
                break;
            default:
                // NOTHING TO DO
        }
    }

    @Override
    public void onClose(WatcherException e) {
        LOGGER.error(e.getMessage(), e);
    }
}
